<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{.Title}}</title>
    <link href="/static/libs/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="/static/libs/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
    <link href="/static/css/app.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="bi bi-database"></i>
                PGM - PostgreSQL管理平台
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/">
                            <i class="bi bi-house"></i>
                            首页
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/api/tables">
                            <i class="bi bi-table"></i>
                            API文档
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-12">
        <!-- 头部信息 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="h3">
                    <i class="bi bi-table"></i>
                    {{.TableName}}
                </h1>
                <p class="text-muted mb-0">
                    {{if .Table.Comment}}{{.Table.Comment}}{{else}}数据表管理{{end}}
                </p>
            </div>
            <div class="btn-group">
                <a href="/" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-left"></i>
                    返回
                </a>
                <a href="/table/{{.TableName}}/create" class="btn btn-success">
                    <i class="bi bi-plus"></i>
                    新增记录
                </a>
                <button class="btn btn-danger" onclick="batchDelete()" id="batchDeleteBtn" style="display:none;">
                    <i class="bi bi-trash"></i>
                    批量删除
                </button>
            </div>
        </div>

        <!-- 搜索和筛选 -->
        <div class="card mb-4">
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label for="search" class="form-label">搜索</label>
                        <input type="text" class="form-control" id="search" placeholder="输入关键词搜索...">
                    </div>
                    <div class="col-md-2">
                        <label for="pageSize" class="form-label">每页显示</label>
                        <select class="form-select" id="pageSize">
                            <option value="10">10</option>
                            <option value="20" selected>20</option>
                            <option value="50">50</option>
                            <option value="100">100</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="orderBy" class="form-label">排序字段</label>
                        <select class="form-select" id="orderBy">
                            <option value="">默认</option>
                            {{range .Table.Columns}}
                            <option value="{{.Name}}">{{.Name}}</option>
                            {{end}}
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="order" class="form-label">排序方向</label>
                        <select class="form-select" id="order">
                            <option value="asc">升序</option>
                            <option value="desc">降序</option>
                        </select>
                    </div>
                </div>
                <div class="mt-3">
                    <button class="btn btn-primary" onclick="searchRecords()" id="searchBtn">
                        <i class="bi bi-search"></i>
                        搜索
                    </button>
                    <button class="btn btn-outline-secondary" onclick="resetSearch()" id="resetBtn">
                        <i class="bi bi-arrow-clockwise"></i>
                        重置
                    </button>
                </div>
            </div>
        </div>

        <!-- 数据表格 -->
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">数据记录</h5>
                    <div>
                        <span id="recordCount" class="text-muted"></span>
                    </div>
                </div>
            </div>
            <div class="card-body p-0 position-relative">
                <!-- 表格加载覆盖层 -->
                <div id="tableLoadingOverlay" class="position-absolute w-100 h-100 d-flex justify-content-center align-items-center bg-white bg-opacity-75" style="z-index: 10; display: none;">
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <div class="mt-2 text-muted">正在加载数据...</div>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover mb-0" id="dataTable">
                        <thead class="table-light">
                            <tr>
                                <th>
                                    <input type="checkbox" id="selectAll" onchange="toggleSelectAll()">
                                </th>
                                {{range .Table.Columns}}
                                <th>
                                    {{.Name}}
                                    {{if .Comment}}
                                        <small class="text-muted">({{.Comment}})</small>
                                    {{end}}
                                    {{if contains $.Table.PrimaryKeys .Name}}
                                        <span class="badge bg-primary">PK</span>
                                    {{end}}
                                    {{if not .IsNullable}}
                                        <span class="badge bg-danger">必填</span>
                                    {{end}}
                                </th>
                                {{end}}
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="tableBody">
                            <!-- 数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- 分页 -->
        <nav aria-label="分页导航" class="mt-4">
            <ul class="pagination justify-content-center" id="pagination">
                <!-- 分页按钮将通过JavaScript动态生成 -->
            </ul>
        </nav>
    </div>
</div>

<!-- 表字段信息（用于JavaScript） -->
<script>
const tableInfo = {
    name: '{{.TableName}}',
    columns: [
        {{range .Table.Columns}}
        {
            name: '{{.Name}}',
            dataType: '{{.DataType}}',
            isNullable: {{.IsNullable}},
            isPrimaryKey: {{contains $.Table.PrimaryKeys .Name}}
        },
        {{end}}
    ],
    primaryKeys: [{{range $.Table.PrimaryKeys}}'{{.}}',{{end}}]
};

let currentPage = {{.Page}};
let currentPageSize = {{.PageSize}};
let totalRecords = 0;
let selectedRecords = [];

// 记录当前正在加载的按钮
let loadingButtons = new Set();

// 页面加载时获取数据
document.addEventListener('DOMContentLoaded', function() {
    // 延迟确保app.js中的函数已加载
    setTimeout(function() {
        loadRecords();
    }, 100);
});

// 加载记录
function loadRecords() {
    // 显示表格加载状态
    showTableLoadingState();

    const search = document.getElementById('search').value;
    const pageSize = document.getElementById('pageSize').value;
    const orderBy = document.getElementById('orderBy').value;
    const order = document.getElementById('order').value;

    const params = new URLSearchParams({
        page: currentPage,
        page_size: pageSize,
        search: search,
        order_by: orderBy,
        order: order
    });

    fetch(`/api/data/${tableInfo.name}?${params}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                renderTable(data.data.data);
                totalRecords = data.data.total;
                updatePagination(data.data);
                updateRecordCount();
                // 数据加载完成，不需要显示成功消息
            } else {
                if (typeof showError === 'function') {
                    showError('加载数据失败: ' + data.message);
                } else {
                    alert('加载数据失败: ' + data.message);
                }
            }
        })
        .catch(error => {
            if (typeof showError === 'function') {
                showError('网络错误: ' + error.message);
            } else {
                alert('网络错误: ' + error.message);
            }
        })
        .finally(() => {
            // 隐藏表格加载状态
            hideTableLoadingState();
            
            // 恢复所有加载中的按钮状态
            restoreAllButtonStates();
        });
}

// 渲染表格
function renderTable(records) {
    const tbody = document.getElementById('tableBody');
    tbody.innerHTML = '';

    if (!records || records.length === 0) {
        tbody.innerHTML = '<tr><td colspan="' + (tableInfo.columns.length + 2) + '" class="text-center text-muted">暂无数据</td></tr>';
        return;
    }

    records.forEach(record => {
        const row = document.createElement('tr');
        
        // 复选框
        const checkboxCell = document.createElement('td');
        const primaryKeyValue = getPrimaryKeyValue(record);
        checkboxCell.innerHTML = `<input type="checkbox" class="record-checkbox" value="${primaryKeyValue}" onchange="updateBatchDeleteButton()">`;
        row.appendChild(checkboxCell);

        // 数据列
        tableInfo.columns.forEach(column => {
            const cell = document.createElement('td');
            const value = record[column.name];
            
            if (value === null || value === undefined) {
                cell.innerHTML = '<span class="text-muted">NULL</span>';
            } else if (column.dataType === 'boolean') {
                cell.innerHTML = value ? '<span class="badge bg-success">true</span>' : '<span class="badge bg-danger">false</span>';
            } else if (typeof value === 'string' && value.length > 50) {
                cell.innerHTML = `<span title="${escapeHtml(value)}">${escapeHtml(value.substring(0, 50))}...</span>`;
            } else {
                cell.innerHTML = escapeHtml(String(value));
            }
            
            row.appendChild(cell);
        });

        // 操作列
        const actionCell = document.createElement('td');
        actionCell.innerHTML = `
            <div class="btn-group btn-group-sm">
                <a href="/table/${tableInfo.name}/edit/${primaryKeyValue}" class="btn btn-outline-primary">
                    <i class="bi bi-pencil"></i>
                </a>
                <button class="btn btn-outline-danger" onclick="deleteRecord('${primaryKeyValue}')">
                    <i class="bi bi-trash"></i>
                </button>
            </div>
        `;
        row.appendChild(actionCell);

        tbody.appendChild(row);
    });
}

// 获取主键值
function getPrimaryKeyValue(record) {
    return record[tableInfo.primaryKeys[0]] || '';
}

// 显示表格加载状态
function showTableLoadingState() {
    if (typeof showTableLoading === 'function') {
        showTableLoading();
    } else {
        // 备用加载显示 - 使用setProperty确保能够覆盖样式
        const overlay = document.getElementById('tableLoadingOverlay');
        if (overlay) {
            overlay.style.setProperty('display', 'flex', 'important');
        }
    }
}

// 隐藏表格加载状态
function hideTableLoadingState() {
    if (typeof hideTableLoading === 'function') {
        hideTableLoading();
    } else {
        // 备用隐藏加载 - 使用setProperty确保能够覆盖样式
        const overlay = document.getElementById('tableLoadingOverlay');
        if (overlay) {
            overlay.style.setProperty('display', 'none', 'important');
        }
    }
}

// 统一的按钮加载状态管理
function setButtonLoading(button, isLoading) {
    if (!button) return;
    
    if (isLoading) {
        // 添加到加载列表
        loadingButtons.add(button);
        
        if (typeof showButtonLoading === 'function') {
            showButtonLoading(button);
        } else {
            // 备用加载显示
            const originalText = button.innerHTML;
            button.setAttribute('data-original-text', originalText);
            button.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>加载中...';
            button.disabled = true;
        }
    } else {
        // 从加载列表中移除
        loadingButtons.delete(button);
        
        if (typeof hideButtonLoading === 'function') {
            hideButtonLoading(button);
        } else {
            // 备用加载恢复
            const originalText = button.getAttribute('data-original-text');
            if (originalText) {
                button.innerHTML = originalText;
                button.removeAttribute('data-original-text');
            }
            button.disabled = false;
        }
    }
}

// 恢复所有按钮状态
function restoreAllButtonStates() {
    loadingButtons.forEach(button => {
        setButtonLoading(button, false);
    });
    loadingButtons.clear();
}

// 搜索记录
function searchRecords() {
    const searchBtn = document.getElementById('searchBtn');
    setButtonLoading(searchBtn, true);
    
    currentPage = 1;
    loadRecords();
}

// 重置搜索
function resetSearch() {
    const resetBtn = document.getElementById('resetBtn');
    setButtonLoading(resetBtn, true);
    
    document.getElementById('search').value = '';
    document.getElementById('pageSize').value = '20';
    document.getElementById('orderBy').value = '';
    document.getElementById('order').value = 'asc';
    currentPage = 1;
    loadRecords();
}

// 删除记录
function deleteRecord(id) {
    if (!confirm('确定要删除这条记录吗？')) return;

    // 找到对应的删除按钮并显示加载状态
    const deleteBtn = event.target.closest('button');
    setButtonLoading(deleteBtn, true);

    fetch(`/api/data/${tableInfo.name}/${id}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            if (typeof showSuccess === 'function') {
                showSuccess('删除成功');
            } else {
                alert('删除成功');
            }
            loadRecords();
        } else {
            if (typeof showError === 'function') {
                showError('删除失败: ' + data.message);
            } else {
                alert('删除失败: ' + data.message);
            }
        }
    })
    .catch(error => {
        if (typeof showError === 'function') {
            showError('网络错误: ' + error.message);
        } else {
            alert('网络错误: ' + error.message);
        }
    })
    .finally(() => {
        // 恢复删除按钮状态
        setButtonLoading(deleteBtn, false);
    });
}

// 批量删除
function batchDelete() {
    const selectedIds = getSelectedRecordIds();
    if (selectedIds.length === 0) {
        if (typeof showError === 'function') {
            showError('请选择要删除的记录');
        } else {
            alert('请选择要删除的记录');
        }
        return;
    }

    if (!confirm(`确定要删除选中的 ${selectedIds.length} 条记录吗？`)) return;

    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    setButtonLoading(batchDeleteBtn, true);

    fetch(`/api/data/${tableInfo.name}/batch`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(selectedIds)
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            if (typeof showSuccess === 'function') {
                showSuccess(`成功删除 ${data.data.success_count} 条记录`);
            } else {
                alert(`成功删除 ${data.data.success_count} 条记录`);
            }
            loadRecords();
            clearSelection();
        } else {
            if (typeof showError === 'function') {
                showError('批量删除失败: ' + data.message);
            } else {
                alert('批量删除失败: ' + data.message);
            }
        }
    })
    .catch(error => {
        if (typeof showError === 'function') {
            showError('网络错误: ' + error.message);
        } else {
            alert('网络错误: ' + error.message);
        }
    })
    .finally(() => {
        // 恢复批量删除按钮状态
        setButtonLoading(batchDeleteBtn, false);
    });
}

// 全选/取消全选
function toggleSelectAll() {
    const selectAllCheckbox = document.getElementById('selectAll');
    const recordCheckboxes = document.querySelectorAll('.record-checkbox');
    
    recordCheckboxes.forEach(checkbox => {
        checkbox.checked = selectAllCheckbox.checked;
    });
    
    updateBatchDeleteButton();
}

// 更新批量删除按钮状态
function updateBatchDeleteButton() {
    const selectedIds = getSelectedRecordIds();
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    
    if (selectedIds.length > 0) {
        batchDeleteBtn.style.display = 'inline-block';
    } else {
        batchDeleteBtn.style.display = 'none';
    }
}

// 获取选中的记录ID
function getSelectedRecordIds() {
    const checkboxes = document.querySelectorAll('.record-checkbox:checked');
    return Array.from(checkboxes).map(cb => cb.value);
}

// 清空选择
function clearSelection() {
    document.getElementById('selectAll').checked = false;
    document.querySelectorAll('.record-checkbox').forEach(cb => cb.checked = false);
    updateBatchDeleteButton();
}

// 更新分页
function updatePagination(data) {
    const pagination = document.getElementById('pagination');
    pagination.innerHTML = '';

    const totalPages = Math.ceil(data.total / data.page_size);
    
    if (totalPages <= 1) return;

    // 上一页
    if (data.page > 1) {
        pagination.innerHTML += `<li class="page-item"><a class="page-link" href="#" onclick="changePage(${data.page - 1})">上一页</a></li>`;
    }

    // 页码
    for (let i = Math.max(1, data.page - 2); i <= Math.min(totalPages, data.page + 2); i++) {
        const activeClass = i === data.page ? 'active' : '';
        pagination.innerHTML += `<li class="page-item ${activeClass}"><a class="page-link" href="#" onclick="changePage(${i})">${i}</a></li>`;
    }

    // 下一页
    if (data.page < totalPages) {
        pagination.innerHTML += `<li class="page-item"><a class="page-link" href="#" onclick="changePage(${data.page + 1})">下一页</a></li>`;
    }
}

// 切换页码
function changePage(page) {
    currentPage = page;
    loadRecords();
}

// 更新记录数量显示
function updateRecordCount() {
    const recordCount = document.getElementById('recordCount');
    recordCount.textContent = `共 ${totalRecords} 条记录`;
}

// 显示成功消息
function showSuccess(message) {
    // 这里可以使用更好的通知组件
    alert('成功: ' + message);
}

// 显示错误消息
function showError(message) {
    // 这里可以使用更好的通知组件
    alert('错误: ' + message);
}

// HTML转义
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 检查数组中是否包含某元素
function contains(array, element) {
    return array.indexOf(element) !== -1;
}
</script>
            </div>
        </div>
    </div>

    <footer class="bg-light py-4 mt-5">
        <div class="container text-center">
            <p class="text-muted mb-0">
                <i class="bi bi-heart-fill text-danger"></i>
                PGM - PostgreSQL管理平台 | 动态数据库管理工具
            </p>
        </div>
    </footer>

    <script src="/static/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="/static/js/app.js"></script>
</body>
</html>